<template>
  <div>
    <el-form ref="form" :model="form" :rules="formRules" label-width="100px" style="width: 90%;">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" placeholder="请选择" style="width: 100%;">
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />

        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" type="textarea" placeholder="1-300个字符" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeesSimple } from '@/api/employees'
import { addDepartment, getDepartDetail, updateDepartments } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 自定义校验规则函数，校验部门的编码的唯一性
    const validCode = (rule, value, callback) => {
      // 验证用户输入的value值，在整个项目中的编码是否已经存在
      let existCodeList = this.originList.map(item => item.code)
      // console.log(existCodeList)\
      // 判断是否是编辑状态，如果是编辑状态则需要把当前的value值在原数组中删除掉
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      // 判断当前value值，是否在数组中存在
      if (existCodeList.includes(value)) {
        callback(new Error(`该部门编码‘${value}’ 已存在，请换一个编码`))
      } else {
        callback()
      }
    }
    // 自定义校验规则函数，如果新增状态，部门名称不能和同级重复
    const validName = (rule, value, callback) => {
      const ExsitNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      // console.log(ExsitNameList, 'ExsitNameList') // ['Java研发部', 'Python研发部', 'Php研发部', '我的部门'] 'ExsitNameList'
      if (ExsitNameList.includes(value)) {
        callback(new Error(`部门名称 '${value}' 已存在`))
      } else {
        callback()
      }
    }
    return {
      list: [], // 保存管理者列表
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      formRules: {
        name: [
          { required: true, message: ' 请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1-50字的部门名称', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: ' 请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1-50字的部门编码', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }

        ],
        manager: [
          { required: true, message: ' 请选择部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: ' 请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '请输入1-300字的部门名称', trigger: 'blur' }

        ]
      }
    }
  },
  created() {
    this.loadEmployeesSimple() // 调用获取部门负责人列表
    if (this.isEdit) {
      this.loadDepartDetail() // 调用查询部门详情
    }
  },
  methods: {
    // 查询部门详情
    async loadDepartDetail() {
      try {
        const { data: res } = await getDepartDetail(this.id)
        console.log('查询部门详情', res)
        // const newForm = {
        //   name: res.name,
        //   code: res.code,
        //   manager: res.manager,
        //   introduce: res.introduce }
        this.form = { ...res }
      } catch (error) {
        console.log(error)
      }
    },
    // 修改数据
    async doEdit() {
      try {
        const res = await updateDepartments(this.form)
        console.log('this.form', this.form)
        console.log('修改数据', res)
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 新增部门
    async doAdd() {
      try {
        // 缺少pdi参数*********  通过父传子把元素的id传过来，当作子元素的pid
        const res = await addDepartment({ pid: this.id, ...this.form })
        console.log('新增部门', res)
        // 通知父组件：关闭弹层，再次更新数据
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取部门负责人列表
    async loadEmployeesSimple() {
      try {
        const res = await getEmployeesSimple()
        console.log('获取部门负责人列表', res)
        this.list = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 确认按钮
    onSubmit() {
      // 还需要兜底校验
      this.$refs.form.validate(valid => {
        // console.log(valid)
        if (!valid) return // 校验失败
        this.isEdit ? this.doEdit() : this.doAdd()
      })
      // this.doAdd()
    },
    // 取消按钮
    onCancel() {
      this.$emit('onEsc')
    }
  }
}
</script>

<style lang="">

</style>
